package com.teacher.service.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.teacher.pojo.entity.PhysicalEducationNormal;
import com.teacher.pojo.excel.PhysicalEducationNormalExcel;
import com.teacher.service.IPerStudentService;
import com.teacher.service.IPhysicalEducationNormalService;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: zfm
 * @Date: 2021/7/30 16:17
 */
public class ExcelPhysicalEducationNormalListener extends AnalysisEventListener<PhysicalEducationNormalExcel> {
    private Long termId;
    private IPhysicalEducationNormalService iPhysicalEducationNormalService;

    private List<PhysicalEducationNormal> physicalEducationNormalList = new ArrayList<>();
    private IPerStudentService iPerStudentService;

    public ExcelPhysicalEducationNormalListener(Long termId, IPhysicalEducationNormalService iPhysicalEducationNormalService, IPerStudentService iPerStudentService) {
        this.termId = termId;
        this.iPhysicalEducationNormalService = iPhysicalEducationNormalService;
        this.iPerStudentService = iPerStudentService;
    }

    @Override
    public void invoke(PhysicalEducationNormalExcel physicalEducationNormalExcel, AnalysisContext analysisContext) {
        if (iPerStudentService.isExit(physicalEducationNormalExcel.getStudentKey())) {
            PhysicalEducationNormal physicalEducationNormal = new PhysicalEducationNormal();
            BeanUtils.copyProperties(physicalEducationNormalExcel, physicalEducationNormal);
            physicalEducationNormal.setTermId(termId);
            physicalEducationNormalList.add(physicalEducationNormal);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    private void saveData() {
        iPhysicalEducationNormalService.saveBatch(physicalEducationNormalList);
    }
}
